package com.xdwanj.dao;

import com.xdwanj.util.JdbcUtil;
import com.xdwanj.util.PageBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.ArrayList;
import java.util.List;

public class BaseDao {

    private JdbcTemplate jdbcTemplate;

    public BaseDao() {
        jdbcTemplate = JdbcUtil.getJdbcTemplate();
    }

    /**
     * 获得 JdbcTemplate 对象
     *
     * @return 返回 JdbcTemplate对象
     */
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    /**
     * 返回分页对象
     *
     * @param sql           查询sql
     * @param queryArgs     查询参数
     * @param rowMapper     dto mapper
     * @param countSql      总量sql
     * @param countArgs     总量参数
     * @param currentPageNo 当前页
     * @param pageSize      每页大小
     * @param <T>           dto
     * @return 分页对象
     */
    public <T> PageBean getCustomerPageDto(String sql, Object[] queryArgs, RowMapper<T> rowMapper, String countSql, Object[] countArgs, int currentPageNo, int pageSize) {

        if (currentPageNo <= 0) {
            throw new RuntimeException("当前页数必须大于1");
        }
        if (pageSize <= 0) {
            throw new RuntimeException("每页大小必须大于1");
        }
        //总共数量
        int totalSize = jdbcTemplate.queryForObject(countSql, countArgs, Integer.class);
        if (totalSize == 0) {
            return PageBean.<T>builder()
                    .content(new ArrayList<T>())
                    .elementTotalCount(0)
                    .currentPageNo(0)
                    .pageSize(0)
                    .totalPageCount(0)
                    .totalCount(0)
                    .build();
        }
        //总页数
        int totalPage = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
        //开始位置
        int offset = (currentPageNo - 1) * pageSize;

        // limit 关键字后面表示查询的范围，offset后面接的表示偏移量
        sql = sql + " limit " + pageSize + " offset " + offset;
        List<T> content = jdbcTemplate.query(sql, queryArgs, rowMapper);
        return PageBean.<T>builder()
                .content(content)
                .elementTotalCount(content.size())
                .totalCount(totalSize)
                .totalPageCount(totalPage)
                .currentPageNo(currentPageNo)
                .pageSize(pageSize)
                .build();
    }


}
